<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="搜索关键词" prop="keyword">
        <el-input
          v-model="queryParams.keyword"
          placeholder="请输入关键词搜索"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除选中</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClear"
        >清空全部</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
        >刷新</el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <!-- 统计信息 -->
    <el-row :gutter="20" class="mb8">
      <el-col :span="8">
        <div class="stats-card">
          <div class="stats-number">{{ total }}</div>
          <div class="stats-label">在线会话总数</div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stats-card">
          <div class="stats-number">{{ uniqueCount }}</div>
          <div class="stats-label">唯一会话数</div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="stats-card">
          <div class="stats-number">{{ filteredTotal }}</div>
          <div class="stats-label">当前显示数</div>
        </div>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      border
      :data="displayList"
      @selection-change="handleSelectionChange"
      style="width: 100%"
      stripe
      highlight-current-row
    >
      <el-table-column type="selection" align="center" width="50" />

      <el-table-column label="序号" type="index" align="center" width="80" />

      <el-table-column label="会话标识" align="center" min-width="200">
        <template slot-scope="scope">
          <div class="session-info">
            <el-tag type="primary" size="medium">
              {{ scope.row.sessionKey }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="会话类型" align="center" width="120">
        <template slot-scope="scope">
          <el-tag
            :type="getSessionTypeTag(scope.row.sessionKey)"
            size="mini"
          >
            {{ getSessionType(scope.row.sessionKey) }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="标识符" align="center" width="150">
        <template slot-scope="scope">
          <span class="identifier">{{ getIdentifier(scope.row.sessionKey) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="重复次数" align="center" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="scope.row.count > 1 ? 'warning' : 'success'"
            size="mini"
          >
            {{ scope.row.count }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag type="success" size="mini">
            在线
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="最后更新时间" align="center" prop="lastUpdateTime" width="160" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="150"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            style="color: #f56c6c"
            @click="handleDelete(scope.row)"
          >断开</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 查看详情对话框 -->
    <el-dialog
      title="WebSocket会话详情"
      :visible.sync="detailOpen"
      width="60%"
      append-to-body
      custom-class="session-detail-dialog"
    >
      <div class="detail-container" v-if="detailData && detailData.sessionKey">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="会话标识" :span="2">
            <el-tag type="primary" size="medium">
              {{ detailData.sessionKey || '-' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="会话类型">
            <el-tag :type="getSessionTypeTag(detailData.sessionKey)" size="mini">
              {{ getSessionType(detailData.sessionKey) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="标识符">
            {{ getIdentifier(detailData.sessionKey) }}
          </el-descriptions-item>
          <el-descriptions-item label="重复次数">
            <el-tag :type="(detailData.count || 0) > 1 ? 'warning' : 'success'" size="mini">
              {{ detailData.count || 0 }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="success" size="mini">在线</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="最后更新时间" :span="2">
            {{ detailData.lastUpdateTime || '-' }}
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-section" style="margin-top: 20px;">
          <h4>会话说明</h4>
          <div class="session-description">
            <p>该会话标识符用于WebSocket连接管理，标识唯一的在线连接实例。</p>
            <p v-if="(detailData.count || 0) > 1" style="color: #e6a23c;">
              <i class="el-icon-warning"></i>
              检测到重复会话，可能存在多个连接实例。
            </p>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailOpen = false">关闭</el-button>
        <el-button type="primary" @click="handleDisconnect(detailData)">断开连接</el-button>
      </div>
    </el-dialog>

    <!-- 分页组件 -->
    <pagination
      v-show="filteredTotal > 0"
      :total="filteredTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="handlePagination"
    />
  </div>
</template>

<script>
import {
  onlineSessionKeys,
  deleteWebSocketLog,
  exportWebSocketLog,
  clearWebSocketLog
} from "@/api/websocketLog";

export default {
  name: "WebSocketLog",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 过滤后总数
      filteredTotal: 0,
      // 唯一会话数
      uniqueCount: 0,
      // 原始数据列表
      rawList: [],
      // 处理后的列表数据
      logList: [],
      // 当前显示的列表（分页后）
      displayList: [],
      // 是否显示详情弹出层
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: ''
      }
    };
  },
  created() {
    // 初始化默认数据
    this.displayList = [];
    this.logList = [];
    this.rawList = [];
    this.getList();
  },
  methods: {
    /**
     * 查询WebSocket在线会话列表
     */
    getList() {
      this.loading = true;
      onlineSessionKeys(this.queryParams).then((response) => {
        // 处理返回的字符串数组数据
        const rawData = response.data || response.rows || response || [];
        this.rawList = Array.isArray(rawData) ? rawData : [];
        
        // 处理数据：统计重复项并转换为对象格式
        this.processData();
        this.loading = false;
      }).catch(() => {
        this.loading = false;
        this.rawList = [];
        this.logList = [];
        this.displayList = [];
        this.total = 0;
        this.filteredTotal = 0;
        this.uniqueCount = 0;
      });
    },

    /**
     * 处理原始数据
     */
    processData() {
      // 统计每个会话的出现次数
      const countMap = {};
      this.rawList.forEach(item => {
        // 确保item是有效的字符串
        if (item && typeof item === 'string') {
          countMap[item] = (countMap[item] || 0) + 1;
        }
      });

      // 转换为对象数组
      this.logList = Object.keys(countMap).map((key, index) => ({
        id: index + 1,
        sessionKey: key || '',
        count: countMap[key] || 0,
        lastUpdateTime: new Date().toLocaleString()
      }));

      // 应用搜索过滤
      this.applyFilter();
      
      // 设置统计数据
      this.total = this.rawList.length;
      this.uniqueCount = this.logList.length;
    },

    /**
     * 应用搜索过滤
     */
    applyFilter() {
      let filteredList = this.logList || [];
      
      // 关键词搜索
      if (this.queryParams.keyword) {
        const keyword = this.queryParams.keyword.toLowerCase();
        filteredList = filteredList.filter(item => 
          item && item.sessionKey && typeof item.sessionKey === 'string' &&
          item.sessionKey.toLowerCase().includes(keyword)
        );
      }

      this.filteredTotal = filteredList.length;
      
      // 分页处理
      const start = (this.queryParams.pageNum - 1) * this.queryParams.pageSize;
      const end = start + this.queryParams.pageSize;
      this.displayList = filteredList.slice(start, end);
    },

    /**
     * 分页变化处理
     */
    handlePagination(pagination) {
      this.queryParams.pageNum = pagination.page;
      this.queryParams.pageSize = pagination.limit;
      this.applyFilter();
    },

    /**
     * 搜索按钮操作
     */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.applyFilter();
    },

    /**
     * 重置按钮操作
     */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /**
     * 多选框选中数据
     */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.sessionKey);
      this.multiple = !selection.length;
    },

    /**
     * 查看按钮操作
     */
    handleView(row) {
      this.detailData = { ...row };
      this.detailOpen = true;
    },

    /**
     * 删除/断开按钮操作
     */
    handleDelete(row) {
      const sessionKeys = row ? [row.sessionKey] : this.ids;
      const message = row 
        ? `是否确认断开会话"${row.sessionKey}"？` 
        : `是否确认断开选中的${sessionKeys.length}个会话？`;
        
      this.$modal
        .confirm(message)
        .then(() => {
          return deleteWebSocketLog(sessionKeys.join(','));
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("操作成功");
        })
        .catch(() => {});
    },

    /**
     * 断开连接操作
     */
    handleDisconnect(row) {
      this.detailOpen = false;
      this.handleDelete(row);
    },

    /**
     * 导出按钮操作
     */
    handleExport() {
      this.download(
        "/api/websocketLog/export",
        {
          ...this.queryParams,
        },
        `websocket_sessions_${new Date().getTime()}.xlsx`
      );
    },

    /**
     * 清空按钮操作
     */
    handleClear() {
      this.$modal
        .confirm('是否确认清空所有WebSocket在线会话？')
        .then(function () {
          return clearWebSocketLog();
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("清空成功");
        })
        .catch(() => {});
    },

    /**
     * 刷新按钮操作
     */
    handleRefresh() {
      this.getList();
      this.$modal.msgSuccess("刷新成功");
    },

    /**
     * 获取会话类型
     */
    getSessionType(sessionKey) {
      if (!sessionKey || typeof sessionKey !== 'string') {
        return '未知';
      }
      if (sessionKey.includes('driver')) {
        return '司机端';
      } else if (sessionKey.includes('user')) {
        return '用户端';
      } else if (sessionKey.includes('admin')) {
        return '管理端';
      }
      return '未知';
    },

    /**
     * 获取会话类型标签样式
     */
    getSessionTypeTag(sessionKey) {
      if (!sessionKey || typeof sessionKey !== 'string') {
        return 'info';
      }
      if (sessionKey.includes('driver')) {
        return 'success';
      } else if (sessionKey.includes('user')) {
        return 'primary';
      } else if (sessionKey.includes('admin')) {
        return 'warning';
      }
      return 'info';
    },

    /**
     * 获取标识符
     */
    getIdentifier(sessionKey) {
      if (!sessionKey || typeof sessionKey !== 'string') {
        return '-';
      }
      // 提取数字部分作为标识符
      const match = sessionKey.match(/\d+/);
      return match ? match[0] : '-';
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.stats-card {
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  color: white;
  margin-bottom: 20px;
  
  .stats-number {
    font-size: 32px;
    font-weight: bold;
    margin-bottom: 8px;
  }
  
  .stats-label {
    font-size: 14px;
    opacity: 0.9;
  }
}

.session-detail-dialog {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.session-detail-dialog >>> .el-dialog__header {
  padding: 16px 20px;
  background: linear-gradient(135deg, #1890ff, #0050b3);
  margin-right: 0;
}

.session-detail-dialog >>> .el-dialog__title {
  color: #ffffff;
  font-weight: 600;
  font-size: 18px;
}

.session-detail-dialog >>> .el-dialog__headerbtn .el-dialog__close {
  color: #ffffff;
  font-size: 20px;
}

.session-detail-dialog >>> .el-dialog__body {
  padding: 30px 20px;
}

.session-detail-dialog >>> .el-dialog__footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  background-color: #fafafa;
}

.detail-container {
  padding: 0;
}

.detail-section {
  h4 {
    color: #303133;
    margin-bottom: 12px;
    font-size: 16px;
  }
}

.session-description {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409eff;
  
  p {
    margin: 8px 0;
    line-height: 1.6;
    color: #606266;
    
    &:last-child {
      margin-bottom: 0;
    }
  }
}

.session-info {
  text-align: center;
  
  .el-tag {
    font-weight: 500;
  }
}

.identifier {
  font-family: 'Courier New', monospace;
  font-weight: bold;
  color: #1890ff;
}

.el-tag {
  margin: 2px;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式优化 */
.el-table {
  font-size: 14px;
}

.el-table >>> .el-table__header th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.el-table >>> .el-table__row:hover > td {
  background-color: #f5f7fa;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-form--inline .el-form-item {
    width: 100%;
    margin-right: 0;
  }
  
  .el-table >>> .el-table__column--selection {
    display: none;
  }
  
  .stats-card {
    margin-bottom: 10px;
  }
}
</style>
